<template>
	<view class="detailsBox" :style=" 'margin-top:' + height + 'px;'">
		<view class="detailsBox_homePage" @click="homePage">
			<view class="iconfont"><u-icon name="arrow-left" color="#fff" size="22"></u-icon></view>
		</view>

		<view class="detailsBox_header">
			<swiper class="uDemoBlock" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
				<swiper-item v-for="(item, index) in goodsDetail.images" :key="index">
					<image :src="item" mode="aspectFill" class="photoSize"></image>
				</swiper-item>
			</swiper>

			<view class="detailsBox_header_goods Column">
				<view class="detailsBox_header_goods_One Row">
					<view class="detailsBox_header_goods_One_moneys">
						￥<span class="detailsBox_header_goods_One_moneys_color">{{goodsDetail.price}}</span>
						<view class="product_Classify Row"> 库存{{goodsDetail.stock}}</view>
					</view>
					<view class="product">已售{{goodsDetail.sales}}</view>
					<!-- <view class="iconfont share">&#xe8b0;</view> -->
				</view>
				<view class="Second Column">
					<view class="productName">{{goodsDetail.name}}</view>
				</view>
				<view class="u-parse">
					<u-parse :content="goodsDetail.content"></u-parse>
				</view>
			</view>
		</view>

		<view class="detailsBox_footer Row">
			<view class="left Row">
				<view class="tit">订购数量</view>
				<view class="quantity_btn">
					<view class="minus_quantity" @click="decrease">-</view>
					<input disabled class="input_quantity" type="number" v-model="quantity" @input="handleInput">
					<view class="add_quantity" @click="increase">+</view>
				</view>
			</view>

			<view class="submit" @click="submit">立即下单</view>
		</view>

		<backTop :isTop="isTop"></backTop>

		<!-- 选择支付方式 -->
		<u-popup customStyle="background-color: #f8f8f8;" :round="12" :show="show" mode="bottom" @close="close"
			@open="submit">
			<view class="popup_box Column">
				<view class="close" @click="close"><u-icon name="close" color="#fff" size="14"></u-icon></view>
				<!-- <view class="title">选择支付方式</view> -->
				<view class="popup-product Row">
					<view style="width: 80px;height: 80px;">
						<image class="photoSize" :src="goodsDetail.images[0]" mode="aspectFill"></image>
					</view>
					<view class="popup-foot Column">
						<view class="popup-price">￥{{goodsDetail.price}}</view>
						<view class="product_Classify Row"> 库存{{goodsDetail.stock}}</view>
					</view>
				</view>

				<!-- delivery_method 配送方式:1=快递,2=线下 -->
				<!-- <view class="deliveryMethod Row">
					<view class="">快递方式</view>
					<view class="Row">
						<view :class="index == delivery_index ? 'active' : 'sizeBox_item'"
							v-for="(item, index) in delivery_method" :key="index" @click="chooseDelivery(item,index)">
							<view class="sizeBox_title">{{item.name}}</view>
						</view>
					</view>
				</view> -->

				<!-- 衣服尺寸 -->
				<!-- <view class="sizeBox Column">
					<view class="sizeBox_head">尺码规格</view>
					<view class="Row">
						<view :class="item == spec ? 'active' : 'sizeBox_item'" v-for="(item, index) in sizeArray"
							:key="index" @click="chooseSpec(item)">
							<view class="sizeBox_title">{{item}}</view>
						</view>
					</view>
				</view> -->

				<!-- 支付方式 -->
				<view class="groupBox">
					<u-radio-group style="width:100%;" placement="column">
						<u-radio iconSize="18" size="24" :label="item.name" :name="item.name"
							v-for="(item, index) in radiolist" :key="index" @change="radioChange(item)"
							style="justify-content: space-between;">
							<view class="payOptions Row">
								<u-icon :name="item.icon" :color="item.color" size="28"></u-icon>
								<view class="optionsText">{{item.name}}</view>
							</view>
						</u-radio>
					</u-radio-group>
				</view>

				<view class="popupFoot Row">
					<view class="payment btn" @click="payment">确认支付</view>
				</view>
			</view>
		</u-popup>

		<!-- 支付二维码弹出层 -->
		<u-popup :round="8" customStyle="width:80%;" :show="codeShow" mode="center" @close="codeClose" @open="codeOpen">
			<view class="codeBox Column">
				<view class="close" data-param="1" @click="codeClose"><u-icon name="close" color="#fff"
						size="20"></u-icon></view>

				<view class="codeBox_code" v-if=" radiolist_name == '微信支付（人工审核）' ">
					<image class="photoSize" :src="wxPay.qrcode" mode="aspectFill"></image>
				</view>
				<view class="codeBox_code" v-if=" radiolist_name == '支付宝备用支付（人工审核）' ">
					<image class="photoSize" :src=" 'https://kffws.hbkfu.com' + wxPay.alipay_payment_qrcode2"
						mode="aspectFill"></image>
				</view>

				<view class="codeBox_tit">{{wxPay.qrcode_tips}}</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		postMenu,
		getMenu
	} from '@/utils/api.js';
	import {
		apiOrderDetail
	} from '@/api/goods.js';
	import {
		apiBindLogs
	} from '@/api/pay.js';
	import {
		apiCreateOrder,
		apiOrderPayment
	} from '@/api/order.js';
	import {
		wxMiniProgramPay
	} from '@/utils/util.js';
	import backTop from '@/components/back-top/back-top.vue';

	export default {
		components: {
			backTop
		},
		data() {
			return {
				height: uni.getSystemInfoSync().statusBarHeight,
				token: uni.getStorageSync('token'),
				show: false,
				codeShow: false,
				isTop: false,

				radiolist: [{
						name: '微信支付',
						icon: 'weixin-circle-fill',
						color: '#23AB3C',
						disabled: true,
						display: 'none',
						type: '3'
					},
					// {
					// 	name: '支付宝支付（自动审核）',
					// 	icon: 'zhifubao-circle-fill',
					// 	color: '#34B4F1',
					// 	disabled: false,
					// 	display: 'block',
					// 	type: '4'
					// },
					// {
					// 	name: '银行卡支付（自动审核）',
					// 	icon: 'rmb-circle-fill',
					// 	color: '#ffde00',
					// 	disabled: true,
					// 	display: 'block',
					// 	type: '5'
					// },
					// {
					// 	name: '微信支付（人工审核）',
					// 	icon: 'weixin-circle-fill',
					// 	color: '#23AB3C',
					// 	disabled: true,
					// 	display: 'block',
					// 	type: '1'
					// },
					// {
					// 	name: '支付宝备用支付（人工审核）',
					// 	icon: 'zhifubao-circle-fill',
					// 	color: '#34B4F1',
					// 	disabled: true,
					// 	display: 'block',
					// 	type: '1'
					// }
				],
				radiolist_name: null,
				payType: '1',
				coverImage: "",

				wxPay: [],

				id: '',
				business_goods_id: '',
				goodsDetail: [],
				quantity: 1, //商品数量
				sizeArray: [], // 尺寸规格
				spec: null, // 尺寸规格
				delivery_method: [ //1=快递,2=线下
					{
						name: "快递",
						num: "1",
					},
					{
						name: "自提",
						num: "2",
					}
				],
				delivery_index: 0, // 尺寸规格
			};
		},
		onLoad(option) {
			this.id = option.id;
			this.getDetail();
		},

		onPageScroll(e) {
			this.isTop = e.scrollTop > 100 ? true : false;
		},

		methods: {
			chooseDelivery(item, index) {
				this.delivery_index = index;
			},

			chooseSpec(item) {
				this.spec = item;
			},

			homePage() {
				uni.navigateBack();
				// uni.navigateTo({
				// 	url: "/pages/index/materialRequisition/materialRequisition"
				// })
			},

			is_wx() { // 判断是否在微信环境中
				let that = this;
				let en = window.navigator.userAgent.toLowerCase();
				// 匹配en中是否含有MicroMessenger字符串
				if (en.match(/MicroMessenger/i) == 'micromessenger') {
					// console.log("当前环境---微信");
					return "WeChat";
				}
				if (en.match(/MicroMessenger/i) != 'micromessenger') {
					// console.log("当前环境---浏览器");
					return "browser";
				}
			},

			payment(type) {
				const that = this;
				const defaultAddress = that.judgeAddress();
				if (!defaultAddress) return;

				uni.showLoading({
					title: '加载中'
				})

				apiCreateOrder({
					goods_id: that.id, // 详情页id
					goods_num: that.quantity,
					address_id: defaultAddress,
					// spec: that.spec,
					// delivery_method: that.delivery_index == 0 ? "1" : "2",
					// pay_type: that.payType, //(3 = 微信支付， 4 = 支付宝, 5=银行卡支付)
				}).then(res => {
					uni.hideLoading()
					if (res.code == 0) {
						uni.$u.toast(res.msg || '操作失败，请稍后重试');
						return;
					}
					that.judgePayType(res.data);
				}).catch(err => {
					uni.hideLoading()
					console.log(err)
				})
			},
			judgeAddress() {
				let defaultAddress = uni.getStorageSync('defaultAddress');
				if (!defaultAddress) {
					uni.$u.toast('请选择收货地址');
					setTimeout(function() {
						uni.navigateTo({
							url: '/pages/mine/shipAddress/shipAddress'
						})
					}, 1000)
					return null;
				}
				return defaultAddress;
			},

			judgePayType(res) {
				let that = this;
				// 2 支付宝form支付
				// 	document.querySelector('body').innerHTML = res
				// 	document.forms[0].submit();
				if (that.payType == 1) {
					that.wxPay = res.payment;
					that.codeOpen();
					that.close();
				} else if (that.payType == 3) { // 微信支付
					wxMiniProgramPay(JSON.parse(res.payment))
						.then(payRes => {
							console.log('支付成功:', payRes.res);
						}).catch(payErr => {
							console.error('支付失败或取消:', payErr);
						})
				} else if (that.payType == 4) { // 支付宝
					const isWeChat = that.is_wx() === "WeChat";
					if (isWeChat) {
						const encodedUrl = btoa(res.payment.rt8_payInfo);
						uni.navigateTo({
							url: `/pages/index/materialRequisition/productDetail/payTransitPage/payTransitPage?url=${encodeURIComponent(encodedUrl)}&id=${this.goodsDetail.id}`
						});
					} else {
						location.href = res.payment.rt8_payInfo;
					}
				} else if (that.payType == 5) { // 银行卡支付
					that.bindLogs(res.order_id);
				}
			},

			// 获取绑卡记录
			bindLogs(order_id) {
				console.log(1)
				apiBindLogs().then(res => {
					if (res.data == "") { // 首次使用银行卡
						uni.navigateTo({
							url: "/pages/index/materialRequisition/productDetail/CardPay/CardPay?order_id=" +
								order_id
						})
					} else { // 绑定
						uni.navigateTo({
							url: "/pages/index/materialRequisition/productDetail/bindPay/bindPay?order_id=" +
								order_id + "&unit_price=" + this.goodsDetail.unit_price
						})
					}
				}).catch(err => {
					console.log(err)
				})
			},

			// 支付方式
			radioChange(item) {
				this.radiolist_name = item.name;
				this.payType = item.type;
			},

			codeClose(e) {
				let param = e.currentTarget.dataset.param;
				if (param) {
					uni.navigateTo({
						url: "/pages/mine/allOrders/allOrders"
					})
					window.location.reload();
					return false;
				}
				this.codeShow = false;
			},
			codeOpen() {
				this.codeShow = true;
			},
			close() {
				this.show = false;
			},
			submit() {
				let that = this;
				let inviter = uni.getStorageSync('inviter');
				let token = uni.getStorageSync('token');
				if (!token) {
					uni.$u.toast('请登录后操作');
					return;
				}
				if (!inviter) {
					uni.$u.toast('请绑定邀请人后操作');
					return;
				}
				that.show = true;
			},
			handleInput(event) {
				const value = parseInt(event.target.value);
				if (!isNaN(value) && value >= 1) {
					this.quantity = value;
				} else {
					this.quantity = 1;
				}
			},
			increase() {
				this.quantity++;
			},
			decrease() {
				if (this.quantity > 1) {
					this.quantity--;
				}
			},

			// 商品详情
			getDetail() {
				let that = this;

				apiOrderDetail({
					goods_id: that.id
				}).then(res => {
					let Obj = res.data;
					let formattedImages = [];

					if (Obj.multiple_spec) {
						const sizeString = Obj.multiple_spec;
						this.sizeArray = sizeString.split(',').map(item => item.trim());
						this.spec = this.sizeArray[0];
					}

					if (Array.isArray(Obj.images)) {
						formattedImages = Obj.images.map(path => this.BASE_URL + path);
					} else {
						formattedImages = [];
					}
					Obj.images = formattedImages;
					this.goodsDetail = Obj;
				}).catch(err => console.log(err))
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F8F8F8 !important;
	}

	.groupBox {
		width: 97%;
		border-radius: 12px;
		background-color: #fff;
		padding: 8px 0 8px 12px;
		marign-top: 12px;

		.payOptions {
			width: 88%;
			justify-content: flex-start;
			padding: 6px 0 6px;

			.optionsText {
				margin-left: 12rpx;
			}
		}
	}


	.detailsBox {
		width: 100%;
		display: flex;
		flex-direction: column;

		&_homePage {
			z-index: 3;
			padding: 20rpx;
			position: fixed;
			top: 6%;
			left: 1%;

			.iconfont {
				border-radius: 8rpx;
				background-color: #d0d0d096;
				padding: 12rpx;
			}
		}

		&_header {
			display: flex;
			flex-direction: column;
			position: relative;
			// padding-bottom: 40rpx;

			.uDemoBlock {
				width: 100%;
				height: 600rpx;
				z-index: 1;
			}

			&_goods {
				flex: 1;
				width: 94.5%;
				background-color: #F8F8F8;
				border-radius: 30rpx 30rpx 0 0;
				padding: 12px;
				padding-bottom: 120rpx;
				overflow: hidden;
				z-index: 2;
				position: absolute;
				top: 34vh;

				.share {
					display: flex;
					font-size: 48rpx;
				}

				&_One {
					justify-content: space-between;
					font-size: 32rpx;

					.product_Classify {
						font-size: 14px;
					}

					&_moneys {
						color: red;
						font-size: 32rpx;


						&_color {
							font-size: 50rpx;
							font-weight: 600;
						}
					}
				}

				.Second {
					padding: 10px 0 10px;
				}

				.productName {
					font-size: 34rpx;
					font-weight: 600;
					padding: 8rpx 0;
				}

				.product {
					color: #a8a8a8;
					font-size: 14px;
					justify-content: space-between;
				}
			}
		}

		.u-parse {
			background-color: #fff;
			padding: 10px;
			border-radius: 12px;
		}

		&_footer {
			justify-content: space-between;
			flex: 1;
			min-width: 95%;
			background-color: white;
			border-top: 2rpx solid #f3f3f3;
			padding: 20rpx;

			position: fixed;
			bottom: 0;
			left: 0;
			z-index: 3;

			.tit {
				margin-right: 20rpx;
			}

			.quantity_btn {
				display: flex;

				.input_quantity {
					width: 60rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
				}

				.add_quantity,
				.minus_quantity {
					width: 60rpx;
					height: 60rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					color: #fff;
					border-radius: 40rpx;
					background-color: #0056FF;
				}

			}

			.line3 {
				padding: 20rpx;

				// border: 1px solid black;
				.line3_position {
					width: 100%;
					display: flex;

					.left {
						width: 30%;
						// border: 1px solid black;
					}

					.right {
						display: flex;
						justify-content: flex-end;
						width: 70%;
						// border: 1px solid black;
					}
				}
			}

			.submit {
				color: #fff;
				border-radius: 50rpx;
				background-color: #0056FF;
				padding: 18rpx 58rpx;
				z-index: 9;
			}
		}

		.codeBox {
			width: 92%;
			align-items: center;
			padding: 40rpx 15px;

			position: relative;

			&_tit {
				width: 94%;
				font-size: 26rpx;
				margin-top: 20px;
			}

			&_code {
				width: 190px;
				height: 230px;
			}

			.close {
				border-radius: 50rpx;
				background-color: #cacaca;
				padding: 12rpx;

				position: absolute;
				top: -16px;
				right: -11px;
			}
		}

		.popup_box {
			overflow: hidden;
			align-items: center;
			border-radius: 10px;
			padding: 0 12px 0 12px;
			position: relative;

			.popup-product {
				justify-content: space-between;
				width: 100%;
				padding-top: 12px;
				padding-bottom: 12px;

				.popup-foot {
					width: 76%;
				}

				.popup-price {
					color: red;
					font-size: 20px;
				}
			}

			.text {
				font-size: 15px;
			}

			.close {
				border-radius: 50rpx;
				background-color: #cacaca;
				padding: 12rpx;

				position: absolute;
				top: 40rpx;
				right: 30rpx;
			}

			.title {
				font-size: 32rpx;
				font-weight: 600;
			}

			.deliveryMethod {
				justify-content: space-between;
				width: 94%;
				background: #fff;
				border-radius: 12px;
				/* padding-top: 24px; */
				padding: 12px;
				margin: 12px 0 12px;

				.active {
					color: #0056FF;
					border: 1px solid #0056FF;
					background-color: #e5eeff;
					border-radius: 6px;
					margin-right: 8px;
					padding: 3px 9px;
				}

				&_item {
					background-color: #f2f2f2;
					border-radius: 6px;
					margin-right: 8px;
					padding: 4px 10px;
				}
			}

			.sizeBox {
				width: 94%;
				background: #fff;
				border-radius: 12px;
				/* padding-top: 24px; */
				padding: 12px;
				margin-top: 12px;

				&_head {
					margin-bottom: 10px;
				}

				.active {
					color: #0056FF;
					border: 1px solid #0056FF;
					background-color: #e5eeff;
					border-radius: 6px;
					margin-right: 8px;
					padding: 3px 9px;
				}

				&_item {
					background-color: #f2f2f2;
					border-radius: 6px;
					margin-right: 8px;
					padding: 4px 10px;
				}
			}

			.popupContent {
				width: 94%;
				border-radius: 12px;
				background-color: #fff;
				padding: 0 12px 12px;
				margin: 12px 0;
			}

			.popupFoot {
				width: 100%;
				justify-content: space-around;

				.payment {
					color: #fff;
					border-radius: 50rpx;
					background-color: #0056FF;
					margin-top: 12px;
				}

				.abandon {
					border-radius: 8rpx;
					border: 2rpx solid #a8a8a8;
				}

				.btn {
					width: 100%;
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 24rpx 0;
				}
			}
		}
	}
</style>